package main

import "sync"

type BrowserHistory struct {
	stack []string
	ptr   int
}

func Constructor(homepage string) BrowserHistory {
	return BrowserHistory{
		stack: []string{homepage},
		ptr:   0,
	}
	sync.Once
}

func (this *BrowserHistory) Visit(url string) {
	this.stack = this.stack[:this.ptr+1] // 丢弃后面的历史
	this.stack = append(this.stack, url)
	this.ptr++
}

func (this *BrowserHistory) Back(steps int) string {
	if steps > this.ptr {
		// 超出范围了
		this.ptr = 0
		return this.stack[0]
	}
	this.ptr -= steps
	return this.stack[this.ptr]
}

func (this *BrowserHistory) Forward(steps int) string {
	if this.ptr+steps >= len(this.stack) {
		this.ptr = len(this.stack) - 1
		return this.stack[this.ptr]
	}
	this.ptr += steps
	return this.stack[this.ptr]
}

func main() {
	hist := Constructor("leetcode.com")
	hist.Visit("google.com")
	hist.Visit("facebook.com")
	hist.Visit("youtube.com")
	println(hist.Back(1))
	println(hist.Back(1))
	println(hist.Forward(1))
	hist.Visit("linkedin.com")
	println(hist.Forward(2))
	println(hist.Back(2))
	println(hist.Back(7))
}
